package com.briup.srms.base.service.impl;

import com.briup.srms.base.bean.BaseRole;
import com.briup.srms.base.bean.BaseUser;
import com.briup.srms.base.bean.BaseUserExample;
import com.briup.srms.base.bean.BaseUserRole;
import com.briup.srms.base.bean.BaseUserRoleExample;
import com.briup.srms.base.bean.extend.BaseUserExtend;
import com.briup.srms.base.dao.BaseUserMapper;
import com.briup.srms.base.dao.BaseUserRoleMapper;
import com.briup.srms.base.dao.extend.BaseUserExtendMapper;
import com.briup.srms.base.service.IBaseUserService;
import com.jacky.base.utils.CustomerException;
import com.jacky.base.utils.PageVM;
import com.briup.srms.base.vm.UserVM;
import com.briup.srms.base.dao.BaseRoleMapper;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

/**
 * @program: kindergarten
 * @description: 用户业务实现类
 * @author: jacky
 * @create: 2020-11-15 15:18
 **/
@Service
public class BaseUserServiceImpl implements IBaseUserService {
    @Resource
    private BaseUserExtendMapper baseUserExtendMapper;
    @Resource
    private BaseUserMapper baseUserMapper;
    @Resource
    private BaseUserRoleMapper baseUserRoleMapper;
    @Resource
    private BaseRoleMapper baseRoleMapper;

    @Override
    public PageVM<BaseUser> pageQuery(int page, int pageSize, String username, String roleName) {
        List<BaseUser> list = baseUserExtendMapper.query(page, pageSize, username, roleName);
        long total = baseUserExtendMapper.count(username, roleName);
        PageVM<BaseUser> pageVM = new PageVM<>(page, pageSize, total, list);
        return pageVM;
    }

    @Override
    public BaseUser login(UserVM userVM) throws CustomerException {
        BaseUserExample example = new BaseUserExample();
        example.createCriteria().andUsernameEqualTo(userVM.getUsername());
        List<BaseUser> list = baseUserMapper.selectByExample(example);
        if (list.size() <= 0) {
            throw new CustomerException("该用户不存在");
        }
        BaseUser user = list.get(0);
        String md5Password = DigestUtils.md5DigestAsHex(userVM.getPassword().getBytes());
        System.out.println(md5Password);
        System.out.println(user.getPassword());
        if (!user.getPassword().equals(md5Password)) {
            throw new CustomerException("密码不匹配");
        }
        return user;
    }

    @Override
    public BaseUserExtend findById(long id) {
        return baseUserExtendMapper.selectById(id);
    }

    @Override
    public List<BaseUser> findAll() {
        return baseUserMapper.selectByExample(new BaseUserExample());
    }

    @Override
    public List<BaseUserExtend> cascadeRoleFindAll() {
        return baseUserExtendMapper.selectAll();
    }

    @Override
    public void saveOrUpdate(BaseUser baseUser) throws CustomerException {
        if (baseUser.getId() != null) {
            String md5Password = DigestUtils.md5DigestAsHex(baseUser.getPassword().getBytes());
            baseUser.setPassword(md5Password);
            baseUserMapper.updateByPrimaryKey(baseUser);
        } else {

            // 判断用户名是否被占用
            BaseUserExample example = new BaseUserExample();
            example.createCriteria().andUsernameEqualTo(baseUser.getUsername());
            List<BaseUser> list = baseUserMapper.selectByExample(example);
            if (list.size() > 0) {
                throw new CustomerException("该用户已经被占用");
            }
            String md5Password = DigestUtils.md5DigestAsHex(baseUser.getPassword().getBytes());
            baseUser.setPassword(md5Password);
            // 初始化
            baseUser.setRegisterTime(new Date().getTime());
            baseUser.setStatus(BaseUserExtend.STATUS_NORMAL);
            baseUserMapper.insert(baseUser);
        }
    }

    @Override
    public void changeStatus(long id, String status) throws CustomerException {
        BaseUser user = this.findById(id);
        if (user == null) {
            throw new CustomerException("该用户不存在");
        }
        user.setStatus(status);
        baseUserMapper.updateByPrimaryKey(user);
    }

    @Override
    public void deleteById(long id) throws CustomerException {
        BaseUser user = this.findById(id);
        if (user == null) {
            throw new CustomerException("该用户不存在");
        }
        baseUserMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void setRoles(long id, List<Long> roles) {
        // 根据userid查询自己的角色
        BaseUserRoleExample example = new BaseUserRoleExample();
        example.createCriteria().andUserIdEqualTo(id);
        // 用户角色关系,获取所有老的角色
        List<BaseUserRole> list = baseUserRoleMapper.selectByExample(example);
        List<Long> oldRoles = new ArrayList<>();
        Iterator<BaseUserRole> iterator = list.iterator();
        while (iterator.hasNext()) {
            oldRoles.add(iterator.next().getRoleId());
        }
        // [1,2,3] -> [3,4] 添加1,2 => [1,2,3,4]
        // 依次判断新角色是否存在于list中，如果不存在则添加
        for (Long roleId : roles) {
            if (!oldRoles.contains(roleId)) {
                BaseUserRole userRole = new BaseUserRole();
                userRole.setRoleId(roleId);
                userRole.setUserId(id);
                baseUserRoleMapper.insert(userRole);
            }
        }
        // [1,2,3] -> [1,2,3,4]   删除 3,4  => [1,2]
        // 依次判断老的角色是否存在于roles中，如果不存在则删除
        for (BaseUserRole userRole : list) {
            if (!roles.contains(userRole.getRoleId())) {
                baseUserRoleMapper.deleteByPrimaryKey(userRole.getId());
            }
        }
    }

    @Override
    public void batchInsert(List<BaseUser> list) throws CustomerException {
        for (BaseUser u : list) {
            // 初始化
            u.setRegisterTime(new Date().getTime());
            u.setStatus(BaseUserExtend.STATUS_NORMAL);
            u.setAvatar("http://121.199.29.84:8888/group1/M00/00/12/rBD-SV-Td6-Aawn0AACq962TS9c719.jpg");
            baseUserMapper.insert(u);

            // 设置默认角色
            BaseUserRole ur = new BaseUserRole();
            ur.setUserId(u.getId());
            ur.setRoleId(6l);// 学生角色
            baseUserRoleMapper.insert(ur);
        }
    }

    @Override
    public void addUserWidthRole(BaseUser user, long roleId) throws CustomerException {
        BaseRole role = baseRoleMapper.selectByPrimaryKey(roleId);
        if (role == null) {
            throw new CustomerException("角色不存在");
        }
        // 初始化用户信息
        user.setRegisterTime(new Date().getTime());
        user.setStatus(BaseUserExtend.STATUS_NORMAL);
        user.setAvatar("http://121.199.29.84:8888/group1/M00/00/12/rBD-SV-Td6-Aawn0AACq962TS9c719.jpg");
        String md5Password = DigestUtils.md5DigestAsHex(user.getPassword().getBytes());
        user.setPassword(md5Password);
        baseUserMapper.insert(user);

        // 维护用户角色关系
        BaseUserRole ur = new BaseUserRole();
        ur.setUserId(user.getId());
        ur.setRoleId(roleId);
        baseUserRoleMapper.insert(ur);
    }

    @Override
    public void alterUserface(long id, String userface) throws CustomerException {
        BaseUser user = baseUserMapper.selectByPrimaryKey(id);
        if (user == null) {
            throw new CustomerException("用户信息不存在");
        }
        user.setAvatar(userface);
        baseUserMapper.updateByPrimaryKey(user);
    }

}
